package com.atguigu.chapter08;

import com.atguigu.bean.HotItem;
import com.atguigu.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.TreeSet;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/16 15:08
 */
public class Flink02_High_Project_HotItem_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> { // 对数据切割, 然后封装到POJO中
                String[] split = line.split(",");
                return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3],
                                        Long.valueOf(split[4]));
            })
            .filter(data -> "pv".equals(data.getBehavior()))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                        @Override
                        public long extractTimestamp(UserBehavior element,
                                                     long recordTimestamp) {
                            return element.getTimestamp() * 1000;
                        }
                    })
            )
            .keyBy(UserBehavior::getItemId)
            .window(TumblingEventTimeWindows.of(Time.hours(1)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long acc) {
                        return acc + 1;
                    }
                    
                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                },
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        Long count = elements.iterator().next();
                        Long wEnd = ctx.window().getEnd();
                        out.collect(new HotItem(key, count, wEnd));
                        
                    }
                }
            )
            .keyBy(HotItem::getWindowEndTime)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                
                private ValueState<Long> wEndState;
                private ListState<HotItem> hotItemState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    hotItemState = getRuntimeContext().getListState(new ListStateDescriptor<HotItem>("hotItemState", HotItem.class));
                    wEndState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("wEndState", Long.class));
                }
                
                @Override
                public void processElement(HotItem hotItem,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    hotItemState.add(hotItem);
                    
                    if (wEndState.value() == null) {
                        // 定时器时间多少
                        long timerTs = hotItem.getWindowEndTime() + 10000;
                        ctx.timerService().registerEventTimeTimer(timerTs);
                        wEndState.update(timerTs);
                        
                    }
                    
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    
                    // 应该使用可以自动排序的集合, 集合只保留前3
                    TreeSet<HotItem> set = new TreeSet<>(new Comparator<HotItem>() {
                        @Override
                        public int compare(HotItem o1, HotItem o2) {
                            int r = o2.getCount().compareTo(o1.getCount());
                            return r == 0 ? 1 : r;  // 因为点击量有可能重复, 为了能够存储重复数据,此处不能返回0
                        }
                    });
                    
                    for (HotItem hotItem : hotItemState.get()) {
                        set.add(hotItem);
                        
                        if (set.size() > 3) {
                            set.pollLast();  // 删除最后一个元素
                        }
                    }
                    
                    // 取top3
                    StringBuilder msg = new StringBuilder();
                    msg
                        .append("-----------------------\n")
                        .append("窗口结束时间: ").append(timestamp - 10000).append("\n");
                    
                    for (HotItem hotItem : set) {
                        msg.append(hotItem).append("\n");
                    }
                    
                    out.collect(msg.toString());
                    
                }
            })
            .print();
        
        env.execute();
        
    }
}
